<?php

namespace Cck\ArticlesSystem\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\ResourceResponse;

class GodApiResponse
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        /** @var JsonResponse $response */
        $response = $next($request);

        if ($this->checkResponse($response, $request)) {
            $content = json_decode($response->getContent(), true);

            if (!array_key_exists('status', $content)) {
                $content['status'] = true;
            }

            $response->setContent(json_encode($content));
        }

        return $response;
    }

    protected function checkResponse($response, $request)
    {
        if ($response instanceof JsonResponse && in_array($response->getStatusCode(), [200, 201])) {
            return true;
        }

        if ($response instanceof ResourceResponse && in_array($response->toResponse($request)->getStatusCode(), [200, 201])) {
            return true;
        }

        return false;
    }
}
